<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools style="margin-bottom: 10px">
        <template #left>
          <el-tag> <i class="el-icon-s-custom" /> 共 {{ total }} 条记录</el-tag>
        </template>
        <template #right>
          <el-button v-arrowBtn="'btn'" type="danger" size="small" round @click="handleDownload">普通Excel导出</el-button>
          <el-button
            type="info"
            size="small"
            round
          >复杂表头Excel导出</el-button>
          <el-button type="warning" size="small" round @click="$router.push('/employees/import/?type=user')">Excel导入</el-button>
          <el-button type="primary" size="small" round @click="addHandler">新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <!-- 具体页面结构 -->
        <el-table :data="tableData" border style="width: 100%">
          <!-- <el-table-column type="index" prop="date" label="序号" align="center" width="50" /> -->
          <el-table-column type="index" prop="date" label="序号" align="center" width="50">
            <template slot-scope="scope">
              <span>{{ (pageObj.page - 1)*pageObj.size + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable prop="username" label="姓名" align="center" />
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template slot-scope="scope">
              <img v-imgError="defaultImg" style="width:50px" :src="scope.row.staffPhoto" alt="">
            </template>
          </el-table-column>
          <el-table-column sortable prop="mobile" align="center" label="手机号" />
          <el-table-column sortable prop="workNumber" align="center" label="工号" />
          <el-table-column sortable prop="formOfEmployment" align="center" label="聘用形式">
            <template slot-scope="scope">
              类型：{{ formatEmployment(scope.row.formOfEmployment) }}
              <!-- ==={{ scope.row.formOfEmployment }} -->
            </template>
          </el-table-column>
          <el-table-column sortable prop="departmentName" align="center" label="部门" />
          <el-table-column sortable prop="timeOfEntry" align="center" label="入职时间" />
          <el-table-column sortable prop="zip" align="center" label="状态">
            <el-switch />
          </el-table-column>
          <el-table-column sortable align="center" label="操作" width="300">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleClick(scope.row)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="roleHandler(scope.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top:20px; text-align:right">
          <el-pagination
            :current-page="pageObj.page"
            :page-size="pageObj.size"
            layout="total, prev, pager, next"
            :total="total"
            background
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog :title="isEdit ? '编辑' : '添加'" :visible.sync="showDialog" width="560px">
      <empDia
        v-if="showDialog"
        :visible.sync="showDialog"
        :row="row"
        :is-edit="isEdit"
        @success="successHandler"
      />
    </el-dialog>
    <!-- 角色弹框 -->
    <el-dialog title="分配角色" :visible.sync="roleShowDialog">
      <setRole v-if="roleShowDialog" ref="role" />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import defaultImg from '@/assets/common/bigUserHeader.png'
import EmployeeEnum from '@/constant/employees'
import empDia from './empDia.vue'
import setRole from './setRole.vue'

export default {
  components: {
    empDia,
    setRole
  },
  data() {
    return {
      defaultImg,
      total: 0,
      showDialog: false,
      roleShowDialog: false,
      isEdit: false,
      row: {},
      tableData: [],
      pageObj: {
        page: 1,
        size: 5
      }

    }
  },
  created() {
    this.loadEmp()
  },
  methods: {
    // 分页切换
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.pageObj.page = val
      this.loadEmp()
    },
    handleClick(row) {
      // console.log(row)
      //  实现页面跳转 =====
      /*
      声明式导航   router-link
      编程式导航   this.$router.push()
      */
      // this.$router.push('/employees/detail/'+row.id)  === path: 'detail/:id',
      //  this.$router.push('/detail/' + row.id) //  path: '/detail/:id',
      // this.$router.push({ path: '/detail/' + row.id })
      // this.$router.push({ name: 'detail', params: { id: row.id }})
      this.$router.push(`/employees/detail/${row.id}`)
    },
    // 无限删除
    // aaa() {
    //   this.tableData.forEach(item => {
    //     if (item.id === '604f764971f93f3ac8f365c2') return
    //     this.handleDelete(item.id)
    //   })
    // },
    // 删除员工
    handleDelete(id) {
      // console.log(id)
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await delEmployee(id)
          // console.log(res)
          if (res.code !== 10000) return
          if (this.tableData.length <= 1) {
            if (this.total === 0) {
              this.pageObj.page = 1
              return
            }
            this.pageObj.page--
          }
          this.loadEmp()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取表格数据
    async loadEmp() {
      const res = await getEmployeeList(this.pageObj)
      // console.log(res)
      if (res.code !== 10000) return
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 聘用形式
    formatEmployment(num) {
      // 从hireType中 通过id找到对应的元素的value
      const item = EmployeeEnum.hireType.find(it => it.id === +num)
      // console.log(num)
      if (item) {
        return item.value
      } else {
        return '不能确定'
      }
      // return  ? '正式' : '非正式'
    },
    // add打开dialog
    addHandler() {
      this.showDialog = true
    },
    successHandler() {
      const num = Math.ceil(this.total / this.pageObj.size)
      console.log(num)
      this.pageObj.page = num
      this.loadEmp()
    },
    // 导出
    async  handleDownload() {
      const res = await getEmployeeList({ page: 1, size: this.total })
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const multiHeader = [['表格', '', '', '', '', '', '', '', '', ''], ['大表格', '', '', '', '', '', '', '', '', '']]
        const merges = ['A1:J1', 'A2:J2']
        const tHeader = ['编号', '密码', '手机号', '姓名', '入职日期', '聘用形式', '转正日期', '工号', '部门', '头像地址']
        const filterVal = ['id', 'password', 'mobile', 'username', 'timeOfEntry', 'formOfEmployment', 'correctionTime', 'workNumber', 'departmentName', 'staffPhoto']
        // const list = this.tableData
        const list = res.data.rows // 导出所有数据
        // console.log(list)
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          multiHeader,
          merges,
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      //       const map = {
      //   'id': '编号',
      //   'password': '密码',
      //   'mobile': '手机号',
      //   'username': '姓名',
      //   'timeOfEntry': '入职日期',
      //   'formOfEmployment': '聘用形式',
      //   'correctionTime': '转正日期',
      //   'workNumber': '工号',
      //   'departmentName': '部门',
      //   'staffPhoto': '头像地址'
      // }
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return '1'
        } else {
          return v[j]
        }
      }))
    },
    // 角色
    roleHandler(id) {
      this.roleShowDialog = true
      this.$nextTick(() => {
        // console.log(this.$refs.role)
        this.$refs.role.id = id
      })
    }
  }
}
</script>
